# from backend.models import *
from backend.common.common_db import *
from backend.common.assertapi import *
from collections import Counter


# 执行接口维度统计表
def statistics_interface_action(interface_pici, environment_id, interface_action, interface_succcess_list,
                                interface_fail_list, progect_id, execute):
    # 1-1列表去重interface_succcess_list = [1, 1, 2]  interface_fail_list=[3,3,4]

    execute = caseType(execute)

    list2 = []
    list2.append(interface_succcess_list)
    list2.append(interface_fail_list)

    for i in list2:

        i_copy = i[:]  # 切片拷贝
        i.clear()
        for each in i_copy:
            if each not in i:
                i.append(each)

    interface_succcess_list = list2[0]
    interface_fail_list = list2[1]

    # 当一个接口多个测试案例得时候，既有执行成功又有执行失败；接口维度记录执行失败；
    for i in interface_succcess_list:
        if i in interface_fail_list:
            interface_succcess_list.remove(i)
        else:
            pass

    # 1-2获取批次
    # print("批次:%s" % interface_pici)

    #     1-3执行的接口名称列表 + 个数
    #     print("执行的接口:%s"%interface_action)
    interface_action_name_list = []
    for i in interface_action:
        interface_action_name = Interfaces.getInterfacesName(i)
        interface_action_name_list.append(interface_action_name)
    # print("执行的接口名称为:%s"%interface_action_name_list)
    # 个数
    interface_action_count = len(interface_action)
    # print("共计本批次执行的总个数：%s"%interface_action_count)

    #     1-4执行成功的接口名称列表 + 个数
    #     print("执行成功的接口:%s" % interface_succcess_list)
    interface_succcess_name_list = []
    for i in interface_succcess_list:
        interface_action_name = Interfaces.getInterfacesName(i)
        interface_succcess_name_list.append(interface_action_name)
    # print("执行成功的接口名称为:%s" % interface_succcess_name_list)
    #     个数
    interface_succcess_count = len(interface_succcess_list)
    # print("接口执行成功的个数统计:%s"%interface_succcess_count)

    # 1-5 执行失败的接口名称列表 + 个数
    # print("执行失败的接口:%s"%interface_fail_list)
    interface_fail_name_list = []
    for i in interface_fail_list:
        interface_action_name = Interfaces.getInterfacesName(i)
        interface_fail_name_list.append(interface_action_name)
    # print("执行失败的接口名称为:%s" % interface_fail_name_list)
    #     个数
    interface_fail_count = len(interface_fail_list)
    # print("接口执行失败的个数统计:%s" % interface_fail_count)

    #   1-6  接口整体的执行结果
    if interface_fail_count == 0:  # 本批次接口全部执行成功
        interface_res = "成功"

    else:  # 本批次接口存在执行失败
        interface_res = "失败"

    #     2.入数据库：环境id，项目id，批次号,总执行的本批次id,总执行的接口名称，执行的接口数量，成功列表id,成功名称，成功数量，失败列表id,失败名称，失败数量，执行结果
    environmentId = Sys_Environment.objects.get(id=environment_id)
    progectId = Sys_Project.objects.get(id=progect_id)
    Interface_Action.addInterfaceAction(progectId, environmentId, interface_pici, interface_action,
                                        interface_action_name_list, interface_action_count,
                                        interface_succcess_list, interface_succcess_name_list, interface_succcess_count,
                                        interface_fail_list, interface_fail_name_list, interface_fail_count,
                                        interface_res, execute)
    return interface_action_count, interface_succcess_count, interface_fail_count, interface_pici, interface_action, interface_succcess_list, interface_fail_list, interface_res


# 执行用例汇总表 + 用例详情表
def statistics_interface_action_detail(interfaces_id, testcase_id, param_in, param_out, http_results, action_condition,
                                       test_case_result, interface_pici):
    # 存储用例执行汇总表
    # 1-1 接口名称
    interface_name = Interfaces.getInterfacesName(interfaces_id)

    # 1-2用例名称
    interface_case_name = Interfaces_Case.getCaseName(testcase_id)

    # 1-3校验内容取值，校验规则，预期值，实际值，四个字段的集合

    check_key_lists = []
    check_condition_lists1 = []
    check_value_lists = []
    out_value_lists = []
    print(http_results)
    print("报错的地方？？？？？？？？？？？")
    for i in http_results:
        check_key = list(i[0].keys())[0]
        check_condition = list(i[0][check_key].keys())[0]
        check_value = i[0][check_key][check_condition]
        out_value = i[1]

        check_key_lists.append(check_key)
        check_condition_lists1.append(check_condition)
        check_value_lists.append(check_value)
        out_value_lists.append(out_value)

    # 存储校验规则时将数字转换成汉字（7=等于）
    check_condition_lists = []
    for i in check_condition_lists1:
        check_condition = check_condition_type(i)
        check_condition_lists.append(check_condition)
    # print(check_condition_lists)

    # 1-4用例整体的执行结果

    if test_case_result == "success":
        interface_res = "成功"
    else:
        interface_res = "失败"

    # 1-5存储用例执行汇总表数据
    interfacesId = Lyzd_Interface.objects.get(id=interfaces_id)
    testcaseId = Lyzd_Interface_Case.objects.get(id=testcase_id)
    InterfaceCase_Action.addInterfaceCaseAction(interface_pici, interfacesId, testcaseId, interface_name,
                                                interface_case_name, check_key_lists, check_condition_lists,
                                                check_value_lists, out_value_lists, interface_res)

    # 用例执行详情存储
    # 2-1取出上条存储数据的id(外键)
    interfacecase_action_id = InterfaceCase_Action.getInterfaceCaseActionID(interface_pici, interface_name,
                                                                            interface_case_name)
    interfacecase_action_id = list(interfacecase_action_id)[0]['id']

    # 2-2本次执行的接口id+ 测试案例id + 此用例的全部的入参 + 全部的出参 + （校验关键字 + 断言分类 +预期值）+实际返回值+每一个断言的执行结果存储
    for http_result in http_results:  # [{'ceshi': {'assertEqual': '100'}}, '', '失败']

        check_key = list(http_result[0].keys())[0]
        check_condition = list(http_result[0][check_key].keys())[0]
        check_value = http_result[0][check_key][check_condition]
        out_value = http_result[1]
        interface_res = http_result[2]

        # 用例详情表校验规则中转换成中文
        check_condition = check_condition_type(check_condition)

        Interface_Action_Detail.addInterfaceActionDetail(interfacecase_action_id,
                                                         interface_case_name,
                                                         check_key,
                                                         check_condition,
                                                         check_value,
                                                         out_value,
                                                         action_condition,
                                                         param_in,
                                                         param_out,
                                                         interface_res)
    # 外键，用例名称存储，（校验关键字 + 断言分类 +预期值）+实际返回值，执行条件，全部的入参 + 全部的出参 ，每一个的执行结果统计
    return "添加成功"


# 删除用例详情表记录 --缓存问题
def del_statistics_interface_action_detail(interface_pici):
    Lyzd_InterfaceCase_Action_ids = InterfaceCase_Action.getInterfaceCaseActionIDs(
        interface_pici)  # 用例汇总表中查询此批次下涉及所有id：[{'id': 15}, {'id': 16}, {'id': 17}, {'id': 18}]

    for Lyzd_InterfaceCase_Action_id in Lyzd_InterfaceCase_Action_ids:
        Interface_Action_Detail.delInterfaceActionDetail(Lyzd_InterfaceCase_Action_id['id'])  # 用例详情表中进行删除操作


# 删除用例汇总表记录 --缓存问题
def del_statistics_interface_action(interface_pici, success_lists):
    for success_interface in success_lists:
        success_interface = int(success_interface)
        InterfaceCase_Action.delInterfaceCaseAction(interface_pici, success_interface)

"""常规校验"""
def common_table_check(interface_res_result_list_totle, interface_pici):
    for interface_res_result in interface_res_result_list_totle:  # [['237', 69, [{'1': '失败'}, {'3': '失败'}], []], ['285', 70, [{'1': '失败'}, {'2': '成功'}], [['成功', '成功', '失败']]]]

        keys_list = []
        for interface_res in interface_res_result[2]:

            for keys, values in interface_res.items():
                keys_list.append(keys)

        if "3" in keys_list:  # 场景三
            interface_res = ""
            pass

        elif "2" in keys_list:  # 场景2
            interface_res = ""
            pass

        else:
            interface_name = "None"
            interface_case_name = "None"
            check_key_lists = "None"
            check_condition_lists = "None"
            check_value_lists = "None"
            out_value_lists = "None(失败原因：执行的接口没有维护常规校验数据)"
            interface_res = "失败"

            interfaces_id = Lyzd_Interface.objects.get(id=interface_res_result[0])
            testcase_id = Lyzd_Interface_Case.objects.get(id=interface_res_result[1])
            InterfaceCase_Action.addInterfaceCaseAction(interface_pici, interfaces_id, testcase_id,
                                                        interface_name,
                                                        interface_case_name,
                                                        check_key_lists,
                                                        check_condition_lists,
                                                        check_value_lists, out_value_lists, interface_res)
    #         全部都是与本接口无关的表，此批次标注为失败

    return interface_res


def common_table_check(interface_res_result_list_totle,
                       interface_pici):  # [['237', 69, [{'1': '失败'}, {'3': '失败'}], []], ['285', 70, [{'1': '失败'}, {'2': '成功'}], [['成功']]]]
    mes_list = []
    sessen_list = []  # 存储场景，是否是全部为场景1
    for interface_res_result in interface_res_result_list_totle:

        mesg_in = []
        if len(interface_res_result[3]) == 0:  # 表示没有场景2；

            # 查看是否全是场景1：
            for sesc in interface_res_result[2]:
                sesc_key = list(sesc.keys())
                sessen_list.append(sesc_key)

            mesg = "失败"
            mesg_in.append(interface_res_result[0])
            mesg_in.append(interface_res_result[1])
            mesg_in.append(mesg)
            mes_list.append(mesg_in)


        else:

            for sesc in interface_res_result[2]:
                sesc_key = list(sesc.keys())
                sessen_list.append(sesc_key)

            #         根据实际执行情况判断接口执行成功或失败
            if "失败" in interface_res_result[3][0]:
                mesg = "失败"
                mesg_in.append(interface_res_result[0])
                mesg_in.append(interface_res_result[1])
                mesg_in.append(mesg)
                mes_list.append(mesg_in)

            else:
                mesg = "成功"
                mesg_in.append(interface_res_result[0])
                mesg_in.append(interface_res_result[1])
                mesg_in.append(mesg)
                mes_list.append(mesg_in)

    # 是否全部是场景1的情况：
    scene_list = []
    for scene in sessen_list:
        scene_list.append(scene[0])

    res = Counter(scene_list)

    count1 = res['1']
    count_totle = len(sessen_list)
    if count1 < count_totle:  # 场景1的个数比总个数场景小，说明不全是场景1,不执行场景1的添加场景

        pass
    else:  # 场景1的个数=总个数场景小，说明全是场景1,新增错误提示信息
        for interfaces_ids in mes_list:
            interfaces_id = interfaces_ids[0]
            testcase_id = interfaces_ids[1]
            interface_name = Interfaces.getInterfacesName(interfaces_id)
            interface_case_name = Interfaces_Case.getCaseName(testcase_id)
            check_key_lists = "None"
            check_condition_lists = "None"
            check_value_lists = "None"
            out_value_lists = "None（失败原因：执行的接口没有维护常规校验数据）"
            interface_res = "失败"

            interfacesId = Lyzd_Interface.objects.get(id=interfaces_id)
            testcaseId = Lyzd_Interface_Case.objects.get(id=testcase_id)

            InterfaceCase_Action.addInterfaceCaseAction(interface_pici, interfacesId, testcaseId, interface_name,
                                                        interface_case_name, check_key_lists, check_condition_lists,
                                                        check_value_lists, out_value_lists, interface_res)
            # print("全部是场景1的情况，入库成功")

    return mes_list

"""常规校验"""
def statistics_interface_action_rewrite(common_table_check1, statistics_interface_result):
    res_lists = []  # ['失败', '失败']
    for common_table_check in common_table_check1:
        # print("样本:%s"%common_table_check)   #['237', 69, '失败']
        res_lists.append(common_table_check[2])
        if common_table_check[2] == "失败":
            # 添加一条失败列表记录，失败数量+1: 本次执行接口个数(不变)+批次号（不变）+本批次执行列表（不变）+成功接口个数（-1） + 失败接口个数（+1）  + 成功列表（去除数据） + 失败列表（增添数据）

            # 1-1 添加失败列表；删除成功列表
            fail_lists = statistics_interface_result[6]  # ['237']
            success_lists = statistics_interface_result[5]
            fail_lists.append(common_table_check[0])
            success_lists.remove(common_table_check[0])
            # print("现在执行成功的列表为:%s,失败的列表为:%s" % (success_lists, fail_lists))

            # 1-2 成功接口的个数,失败的个数
            success_count = len(success_lists)
            fail_count = len(fail_lists)
            # print("现在执行成功的个数为:%s,失败的个数为:%s" % (success_count, fail_count))

            # 1-3查询接口名称
            if success_count != 0:  # 有成功接口
                interface_aciton_succcess_name = []
                for success_interfaces_id in success_lists:
                    interfaces_name = Interfaces.getInterfacesName(success_interfaces_id)
                    interface_aciton_succcess_name.append(interfaces_name)

            else:  # 无成功接口
                interface_aciton_succcess_name = []

            # print("现在成功接口的接口名称列表为:%s"%interface_aciton_succcess_name)

            if fail_count != 0:
                interface_aciton_fail_name = []
                for fail_interfaces_id in fail_lists:
                    interfaces_name = Interfaces.getInterfacesName(fail_interfaces_id)
                    interface_aciton_fail_name.append(interfaces_name)

            else:  # 无成功接口
                interface_aciton_fail_name = []

            # print("现在失败接口的接口名称列表为:%s" % interface_aciton_fail_name)

            # 1-3更新数据
            Interface_Action.updateInterfaceAction(statistics_interface_result[3], success_lists, success_count,
                                                   interface_aciton_succcess_name, fail_lists, fail_count,
                                                   interface_aciton_fail_name)

            pass
        else:

            success_count = statistics_interface_result[1]
            fail_count = statistics_interface_result[2]

    # 整体执行情况判断
    if "失败" in res_lists:
        interface_res = "失败"
        # 更新状态批次整体状态 + 接口最终执行结果
        Interface_Action.updateInterfaceRes(statistics_interface_result[3], interface_res)
        #     查询此时成功个数及失败个数
        success_count = Interface_Action.getCountList(statistics_interface_result[3])[0][
            'interface_aciton_succcess_count']
        fail_count = Interface_Action.getCountList(statistics_interface_result[3])[0]['interface_aciton_fail_count']



    else:
        interface_res = "成功"
        # print("全部是成功，不必更新状态")

    interface_message = {
        "pici": statistics_interface_result[3],
        "interface_action_count": statistics_interface_result[0],
        "success_count": success_count,
        "fail_count": fail_count

    }

    return interface_message


# 将执行表中得用例分类转换成中文展示
def caseType(case_type):
    if case_type == "0":
        case_type = "疏通测试"
    elif case_type == "1":
        case_type = "逻辑测试"
    elif case_type == "2":
        case_type = "常规校验"
    else:
        case_type = "全部"

    return case_type

# 暂时屏蔽
# def common_table_check(interface_res_result_list_totle):
#     mes_list = []
#     for interface_res_result in interface_res_result_list_totle:
#         print(interface_res_result)
#         mesg_in = []
#         if interface_res_result[3] == []: #表示没有场景2；
#             print("表示没有场景2")
#             pass
#         else:
#             res_list = interface_res_result[3][0]
#
#             if "失败" in res_list:
#                 mesg = "失败"
#                 mesg_in.append(interface_res_result[0])
#                 mesg_in.append(interface_res_result[1])
#                 mesg_in.append(mesg)
#                 mes_list.append(mesg_in)
#
#             else:
#                 mesg = "成功"
#                 mesg_in.append(interface_res_result[0])
#                 mesg_in.append(interface_res_result[1])
#                 mesg_in.append(mesg)
#                 mes_list.append(mesg_in)
#
#
#     print("返回值为:%s"%mes_list)
#     return mes_list
#


# 重写执行接口维度统计表（常规校验时根据实际统计结果进行修改返回值）
